package cn.mastor.liaotian;

import cn.mastor.Enum.MsgActionEnum;
import cn.mastor.domain.Msg;
import cn.mastor.netty.ChatMsg;
import cn.mastor.netty.DataContent;
import cn.mastor.netty.UserChanelRel;
import cn.mastor.service.IMsgService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Dragon Wu
 * @since 2022-10-17 13:53
 **/
@Component
@ChannelHandler.Sharable  //在多线程的环境下使用
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Autowired
    IMsgService msgService;
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
 
    //广播
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String content = msg.text();
        System.out.println(content);
        DataContent dataContent = JSONObject.parseObject(content, DataContent.class);
        System.out.println(dataContent);
        Integer action = dataContent.getAction();
        Channel channel = ctx.channel();
        if (action.equals(MsgActionEnum.CINNECT.type)){
            String senderId = dataContent.getChatMsg().getSenderId();
            UserChanelRel.put(senderId,channel);
            Wrapper<Msg> wrapper=new EntityWrapper<>();
            wrapper.eq("type",0);
            wrapper.eq("receiverId",senderId);
            List<Msg> msgs = msgService.selectList(wrapper);
            for (Msg s:msgs
                 ) {
                s.setType(1);
                msgService.updateById(s);
                UserChanelRel.get(senderId).writeAndFlush(
                        new TextWebSocketFrame(
                                s.getTime()+":"+s.getMsg()
                        )
                );
            }
//            System.out.println("这是chnnel"+UserChanelRel.get(senderId));
        }else if (action.equals(MsgActionEnum.CHAT.type)){
            ChatMsg chatMsg = dataContent.getChatMsg();
            Msg msg1 = new Msg();
//            msg1.setTime(new Date());
            BeanUtils.copyProperties(chatMsg,msg1);
            String msgContent = chatMsg.getMsg();
            String senderId = chatMsg.getSenderId();
            String receiverId = chatMsg.getReceiverId();
//            System.out.println("这是"+receiverId);
            Integer save = msgService.save(chatMsg);
            chatMsg.setMsgId(save.toString());
            DataContent dataContent1 = new DataContent();
            dataContent1.setChatMsg(chatMsg);
            Channel re = UserChanelRel.get(receiverId);
            if (re==null){
                msg1.setType(0);
                msg1.setTime(new Date());
                msgService.insert(msg1);
                UserChanelRel.get(senderId).writeAndFlush(
                        new TextWebSocketFrame(
                                "用户不在线"
                        )
                );
            }else {
                Channel find1 = channels.find(re.id());
                if (find1!=null){
                    re.writeAndFlush(
                            new TextWebSocketFrame(
                                    String.valueOf(JSONObject.toJSON(dataContent1.getChatMsg().getMsg()))
                            )
                    );
                }
            }
        }else if (action.equals(MsgActionEnum.SIGNED.type)){
            String msgIdStr = dataContent.getExtand();
            String[] msgIds = msgIdStr.split(",");
            ArrayList<Msg> ids = new ArrayList<>();
            for (String mid:msgIds
                 ) {
                if (!mid.isEmpty()){
                    Msg msg1 = msgService.selectById(Integer.getInteger(mid));
                    msg1.setType(1);
                    ids.add(msg1);
                }
            }
            if (!ids.isEmpty() && ids.size()>0){
                msgService.updateBatchById(ids);
            }
        }else if (action.equals(MsgActionEnum.MEEPALIVE.type)){

        }
//        Channel iChannel = ctx.channel();
//        for (Channel channel : channels) {
//            if (channel != iChannel) {
//                channel.writeAndFlush(new TextWebSocketFrame(ctx.channel().remoteAddress() + content));
//            } else {
//                channel.writeAndFlush(new TextWebSocketFrame("我自己:" + content));
//            }
//        }
    }
 
    //进入
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        for (Channel channel : channels) {
            System.out.println(channel.id());
            channel.writeAndFlush(new TextWebSocketFrame(ctx.channel().remoteAddress() + "进入聊天室"));
        }
        channels.add(ctx.channel());
    }
 
    //退出
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        channels.remove(ctx.channel());
        for (Channel channel : channels) {

            channel.writeAndFlush(new TextWebSocketFrame(ctx.channel().remoteAddress() + "退出聊天室"));
        }
    }
}
